﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using crmbl.Azure.Globals;

namespace cmbl.Azure.Web.Mockup
{
    public partial class Dashboard : System.Web.UI.Page
    {

        private SqlHelper _sql;

        protected void Page_Load(object sender, EventArgs e)
        {
            _sql = new SqlHelper(ConfigurationManager.ConnectionStrings["AzureDataConnectionString"].ConnectionString);

            if (!IsPostBack)
            {

                //Populate Events
                txtStartDateTime.Text = "07/11/2012 00:00:00";
                txtEndDateTime.Text = "07/13/2012 00:00:00";

                // Populate Performance
                PopulateDefaultPerformanceCounters();

                GeneratePerformanceValues();
            }
        }

        private void PopulateDefaultPerformanceCounters()
        {
            
            PopulateDropDown("SELECT * FROM [Role]", dropCounterObject, "RoleName", "RoleRowId");
        }

        public DateTime ConvertJavascriptDateTimeToDotNet(double javascriptDateTime)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(javascriptDateTime);
        }

        public double ConvertDateTimeToJavascriptDateTime(DateTime dateTimeUTC)
        {
            return dateTimeUTC.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }

        private void PopulateDropDown(String query, DropDownList drop, String textField, String valueField)
        {
            drop.DataValueField = valueField;
            drop.DataTextField = textField;

            drop.DataSource = _sql.RunQueryGetDataTable(query);
            drop.DataBind();
        }


        private void GeneratePerformanceValues()
        {
            String qProcessorUtilization = @"
                    Select DateTimeUTC, SampleValue
                    From vw_PerformanceSample_Detailed A
                    Where RoleRowId = 10
	                    And A.ObjectName = 'Processor'
	                    And A.CounterName = '% Processor Time'
	                    And A.InstanceName = '_Total'
	                    And A.DateTimeUTC > GETUTCDATE()-2
                    Order By A.DateTimeUTC";

            String qRequestPerSecond = @"
                    Select DateTimeUTC, SampleValue
                    From vw_PerformanceSample_Detailed A
                    Where RoleRowId = 10
	                    And A.ObjectName = 'ASP.NET Applications'
	                    And A.CounterName = 'Requests/Sec'
	                    And A.InstanceName = '__Total__'
	                    And A.DateTimeUTC > GETUTCDATE()-2
                    Order By A.DateTimeUTC";

            DataTable dtProce = _sql.RunQueryGetDataTable(qProcessorUtilization);
            dtProce.TableName = "Processor Utilization";

            DataTable dtRequest = _sql.RunQueryGetDataTable(qRequestPerSecond);
            dtRequest.TableName = "Request/sec";

            String procValue = GenerateJavascriptArrayValue(dtProce);
            String reqValue = GenerateJavascriptArrayValue(dtRequest);

            StringBuilder chartHtml = new StringBuilder();

            chartHtml.Append("<div id=\"placeholder\" style=\"width:100%;height:300px;\"></div>");


            chartHtml.Append("<script type=\"text/javascript\">");
                chartHtml.Append(@"$(function () {
                    var perfValues1 = [" + procValue + @"];
                    var perfValues2 = [" + reqValue + @"];

                    function euroFormatter(v, axis) {");
                        chartHtml.Append("return v.toFixed(axis.tickDecimals) + \"€\";");
                    chartHtml.Append(@"}

                    function doPlot(position) { ");
                    
                        chartHtml.Append("$.plot($(\"#placeholder\"), ");
                        chartHtml.Append("[{ data: perfValues1, label: \"Processor Utilization\", color: \"#71c73e\" }, ");
                        chartHtml.Append("{ data: perfValues2, label: \"Request/sec\", color: \"#77b7c5\" ,  yaxis: 2 }], ");
                           chartHtml.Append(@"{
                               xaxes: [{ mode: 'time' }],
                               yaxes: [{ min: 0 },
                                        {
                                            ");
                                            chartHtml.Append("alignTicksWithAxis: position == \"right\" ? 1 : null, ");
                                            chartHtml.Append(@"position: position
                                        }],
                               legend: { position: 'sw' }
                           });
                    } ");

                    chartHtml.Append("doPlot(\"right\"); ");

                    chartHtml.Append("$(\"button\").click(function () { ");
                    chartHtml.Append(@"
                        doPlot($(this).text());
                    });
                });
            </script>
            ");

            litChart.Text = chartHtml.ToString();

        }

        private String GenerateJavascriptArrayValue(DataTable dt)
        {
            StringBuilder s = new StringBuilder();

            foreach (DataRow row in dt.Rows)
            {
                s.Append(String.Format("[{0},{1}],",ConvertDateTimeToJavascriptDateTime((DateTime)row["DateTimeUTC"]),(double)row["SampleValue"]));
            }

            if (s.ToString().Length > 0)
            {
                return s.ToString().Substring(0, s.ToString().Length - 1);
            }

            return "";
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            DateTime startDateTime = Convert.ToDateTime(txtStartDateTime.Text).ToUniversalTime();
            DateTime endDateTime = Convert.ToDateTime(txtEndDateTime.Text).ToUniversalTime();

            Dictionary<String, object> p = new Dictionary<string, object>();

            p.Add("@StartDateTime", startDateTime);
            p.Add("@EndDateTime", endDateTime);

            gridEvents.DataSource = null;
            gridEvents.DataBind();

            gridEvents.DataSource = _sql.RunQueryGetDataTable("SELECT * FROM vw_LogEntry WHERE DateTimeUTC > @StartDateTime AND DateTimeUTC < @EndDateTime",p); ;
            gridEvents.DataBind();
        }
    }
}